package com.example.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.support.atomic.RedisAtomicLong;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * description: 基于redis  实现分布式全局id
 * Create with Intellij idea
 * User:mingtian
 * Date:2018/11/29
 * Time:21:33
 */

@RestController
public class OrderController {

    @Autowired
    private RedisTemplate redisTemplate;

    //前缀=当前日期=2018112921303030-5位自增id(高并发情况下  先天性安全)
    //在相同毫秒情况下 最多只能生成100000-1 个订单号
    @RequestMapping("/getOrder")
    public String getOrder(String key) {
        //id 自增
        RedisAtomicLong redisAtomicLong = new RedisAtomicLong(key, redisTemplate.getConnectionFactory());
        //自增后的id
        long orderId = redisAtomicLong.incrementAndGet();
        //填充5位数的id  1代表是1开始，0代表填充的数字，5代表总共5位数，d代表整数
        //String id=String.format("%1$05d",orderId);
        String id = String.format("%05d", orderId);
        return id;
    }


    @RequestMapping("/order1")
    public String order1(String key) {
        RedisAtomicLong redisAtomicLong = new RedisAtomicLong(key, redisTemplate.getConnectionFactory());
        // 起始值
        //redisAtomicLong.set(1);

        // 设置步长加10
        redisAtomicLong.addAndGet(9);
        String id = prefix() + "-" + redisAtomicLong.incrementAndGet();
        return id;
    }

    public static String prefix() {
        String temp_str = "";
        Date dt = new Date();
        // 最后的aa表示“上午”或“下午” HH表示24小时制 如果换成hh表示12小时制
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        temp_str = sdf.format(dt);
        return temp_str;
    }

}
